from datetime import date, timedelta

from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.users.models import Users


class UserSumCountView(APIView):
    '''
    获取用户总数
    '''
    # 添加权限为管理员认证
    permission_classes = [IsAdminUser]

    def get(self, request):
        count = Users.objects.filter().count()

        return Response({"count": count})


class UserDailyActiveCountView(APIView):
    '''
    获取日活用户
    '''
    # 添加权限为管理员认证
    permission_classes = [IsAdminUser]
    def get(self, request):
        # 获取当前日期
        today = date.today()

        count = Users.objects.filter(last_login__gte=today).count()

        return Response({"count": count})


class UserDailyOrderCountView(APIView):
    # 添加权限为管理员认证
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        today = date.today()
        # 获取下单用户数量
        count = Users.objects.filter(orderinfo__create_time__gte=today).count()

        return Response({"count": count})


class UserDayNewCreateCount(APIView):
    '''
    获取日增用户
    '''
    # 添加权限为管理员认证
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        today = date.today()

        count = Users.objects.filter(date_joined__gte=today).count()

        return Response({"count": count})


class UserMonthCountView(APIView):
    '''
    月增用户统计
    '''
    # 添加权限为管理员认证
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取到一个月前的日期
        start_data = date.today() - timedelta(days=30)

        date_ls = []
        for i in range(30):
            data = start_data + timedelta(days=i)

            next_data = start_data + timedelta(days=i + 1)
            # 遍历30次 获取每一天的用户注册数量
            count = Users.objects.filter(date_joined__gte=data, date_joined__lt=next_data).count()

            date_ls.append({
                'count': count,
                'date': data
            })

        return Response(date_ls)
